#!/usr/bin/env bash
# 主菜单：只负责导航到各子菜单
set -Eeuo pipefail

# ===== 颜色 =====
BOLD="\033[1m"
RED="\033[1;31m"
GREEN="\033[1;32m"
YELLOW="\033[1;33m"
BLUE="\033[1;34m"
CYAN="\033[1;36m"
RESET="\033[0m"

# ===== 高亮选中项回显 =====
pick() { echo -e "\n${GREEN}${BOLD}▶ 已选择：$1${RESET}\n"; }

# ===== 运行函数（若未实现则占位提示） =====
run_or_stub() {
  local fn="$1"; shift || true
  if declare -F "$fn" >/dev/null 2>&1; then
    "$fn" "$@"
  else
    echo -e "${YELLOW}[占位提示]${RESET} 函数 ${BOLD}${fn}${RESET} 未实现。"
  fi
}

# ===== 加载公共与功能模块 =====
if [[ -r "./actions/_common.sh" ]]; then
  # shellcheck disable=SC1091
  source "./actions/_common.sh"
else
  echo -e "${YELLOW}[WARN]${RESET} 未找到 ./actions/_common.sh，继续以精简模式运行。"
fi

# 按需增减：把你现有的 actions 模块都列上
for f in mirrors.sh sysupdate.sh install_basic.sh install_net.sh install_dev.sh \
         install_docker.sh install_node.sh install_nginx.sh install_ssh_fw.sh \
         xui_3xui.sh install_gost.sh net_tools.sh optimize.sh dns_tools.sh
do
  if [[ -r "./actions/$f" ]]; then
    # shellcheck disable=SC1091
    source "./actions/$f"
  else
    echo -e "${YELLOW}[WARN]${RESET} 模块缺失：actions/${f}"
  fi
done

# ===== 加载子菜单（只负责界面与分发） =====
mkdir -p menus
for mf in system.sh software.sh network.sh optimize.sh dns.sh; do
  if [[ -r "./menus/$mf" ]]; then
    # shellcheck disable=SC1091
    source "./menus/$mf"
  else
    echo -e "${YELLOW}[WARN]${RESET} 子菜单缺失：menus/${mf}"
  fi
done

# ===== 主菜单渲染 =====
show_main_menu() {
  clear
  echo -e "${CYAN}==============================${RESET}"
  echo -e "   ${GREEN}Linux VPS 一键工具箱 v1.5${RESET}"
  echo -e "${CYAN}==============================${RESET}"
  echo ""
  echo -e "${YELLOW}【主菜单】${RESET}"
  echo -e "  ${GREEN}1.${RESET} 系统管理"
  echo -e "  ${GREEN}2.${RESET} 软件安装"
  echo -e "  ${GREEN}3.${RESET} 网络工具"
  echo -e "  ${GREEN}4.${RESET} 系统优化"
  echo -e "  ${GREEN}5.${RESET} DNS 工具"
  echo ""
  echo -e "  ${GREEN}0.${RESET} 退出"
  echo -e "${CYAN}==============================${RESET}"
}

# ===== 主循环（返回主菜单不再额外按回车）=====
while true; do
  show_main_menu
  read -rp "请选择 [0-5]: " choice
  case "$choice" in
    1) pick "系统管理"; system_menu_loop ;;
    2) pick "软件安装"; software_menu_loop ;;
    3) pick "网络工具"; network_menu_loop ;;
    4) pick "系统优化"; optimize_menu_loop ;;
    5) pick "DNS 工具"; dns_menu_loop ;;
    0) echo -e "${RED}${BOLD}退出工具箱${RESET}"; exit 0 ;;
    *) echo -e "${RED}${BOLD}❌ 无效输入，请重试${RESET}"; sleep 1 ;;
  esac
  # 子菜单返回后，直接继续下一轮循环显示主菜单；不再暂停等待回车
done
